#region - Class details -
/*  
 *  Developer   : Wicus Botha
 *  Description : 
 *  History     : WB - 2008-03-03 - Created
 */
#endregion

using System;
using System.IO;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Drawing;
using System.Globalization;
using System.Security.Cryptography;
using System.Windows.Forms;

namespace IQ.BaseWindows
{
    public static class General
    {
        #region - Private variables - 
        private const string globePath = @"Resources\FormGlobe1.ico";
        #endregion 

        #region - Private methods - 
        private static bool setThemeGrid(DataGridView grd)
        {
            if (grd != null)
            {
                SetGridViewColor(grd);
                grd.AlternatingRowsDefaultCellStyle.Font = FormSettings.DetailFont;
                grd.RowsDefaultCellStyle.Font = FormSettings.DetailFont;
                grd.ColumnHeadersDefaultCellStyle.Font = FormSettings.SubHeadingFont;
                grd.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
                grd.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
                return true;
            }
            else
                return false;
        }        
        private static bool setThemeComboBox(ComboBox cbx, bool addEvents)
        {
            if (cbx != null)
            {
                cbx.FlatStyle = FlatStyle.Flat;
                cbx.BackColor = FormSettings.InputBackColor;
                if (addEvents)
                {
                    cbx.Enter += Txt_Enter;
                    cbx.Leave += Txt_Leave;
                }
                return true;
            }
            else
                return false;
        }
        private static bool setThemeButton(Button btn)
        {
            if (btn != null)
            {
                btn.BackColor = FormSettings.ButtonBackColor;
                return true;
            }
            else
                return false;
        }
        private static bool setThemeLabel(Label lbl)
        {
            if (lbl != null)
            {
                lbl.BackColor = Color.Transparent;
                lbl.ForeColor = FormSettings.LabelTextColor;
                return true;
            }
            else
                return false;
        }
        private static bool setThemeToolStrip(ToolStrip tls)
        {
            if (tls != null)
            {
                tls.GripStyle = ToolStripGripStyle.Hidden;
                tls.BackColor = FormSettings.ToolBarBackColor;
                return true;
            }
            else
                return false;
        }
        #endregion 

        public enum HeadingTag : int
        {
            Ignore = -5,
            FormatStart = -2,
            Default = 0,
            Subheading = -1,
            Heading = 1,
            FormatEnd = 2
        }
        public static bool SetThemeTextBox(TextBoxBase txt, bool addEvents)
        {
            if (txt != null)
            {
                txt.BorderStyle = BorderStyle.FixedSingle;
                if (txt.ReadOnly)
                    txt.BackColor = FormSettings.FormBackColor;
                else
                    txt.BackColor = FormSettings.InputBackColor;
                if (addEvents)
                {
                    txt.Enter += Txt_Enter;
                    txt.Leave += Txt_Leave;
                }
                return true;
            }
            else
                return false;
        }

        #region - Public properties / variables -
        public static int DefaultGridHeaderRowHeight = 32;
        public static int DefaultGridRowHeight = 23;
        #endregion

        #region - Public methods -
        /// <summary>
        /// Show a message box with pre-defined buttons
        /// </summary>
        /// <param name="sMessage">Message to show</param>
        /// <param name="iWhat">Type of box: E=Error box [Ok], F=Confirm box [Yes,No,Cancel],
        ///  I=Information box [Ok], C=Confirm box [Yes,No], W=Warning box [Ok], X=Warning box [Yes,No]</param>
        /// <returns></returns>
        public static DialogResult MesDlg(string sMessage, char iWhat)
        {
            switch (iWhat)
            {
                case 'E': return MessageBox.Show(sMessage, "Error message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                case 'F': return MessageBox.Show(sMessage, "Confirm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                case 'I': return MessageBox.Show(sMessage, "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                case 'C': return MessageBox.Show(sMessage, "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                case 'W': return MessageBox.Show(sMessage, "Warning message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                case 'X': return MessageBox.Show(sMessage, "Warning message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                default: return DialogResult.None;
            }
        } // end MesDlg
        /// <summary>
        /// Show a input box with pre-defined buttons (Ok, Cancel)
        /// </summary>
        /// <param name="title">Input box form title</param>
        /// <param name="promptText">Question to ask</param>
        /// <param name="value">Default value</param>
        /// <returns></returns>
        public static DialogResult InputBox(string title, string promptText, ref string value)
        {
            Form form = new Form();
            Label label = new Label();
            TextBox textBox = new TextBox();
            Button buttonOk = new Button();
            Button buttonCancel = new Button();

            form.Text = title;
            label.Text = promptText;
            textBox.Text = value;

            buttonOk.Text = "OK";
            buttonCancel.Text = "Cancel";
            buttonOk.DialogResult = DialogResult.OK;
            buttonCancel.DialogResult = DialogResult.Cancel;

            label.SetBounds(9, 20, 372, 13);
            textBox.SetBounds(12, 36, 372, 20);
            buttonOk.SetBounds(228, 72, 75, 23);
            buttonCancel.SetBounds(309, 72, 75, 23);

            label.AutoSize = true;
            textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
            buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

            form.ClientSize = new Size(396, 107);
            form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
            form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
            form.FormBorderStyle = FormBorderStyle.FixedDialog;
            form.StartPosition = FormStartPosition.CenterScreen;
            form.MinimizeBox = false;
            form.MaximizeBox = false;
            form.AcceptButton = buttonOk;
            form.CancelButton = buttonCancel;

            DialogResult dialogResult = form.ShowDialog();
            value = textBox.Text;
            return dialogResult;
        }
        public static string GetPCdetails()
        {
            string host = System.Net.Dns.GetHostName();
            string ipAdr = "";
            System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(host);
            System.Net.IPAddress[] addr = ipEntry.AddressList;
            foreach (System.Net.IPAddress ip in addr)
            {
                if (!ip.IsIPv6LinkLocal)
                {
                    ipAdr = ip.ToString();
                    break;
                }
            }
            return "PC: " + host + "; IP:" + ipAdr;
        }
        public static bool AuthenticateUser(string ldapServer, string domain, string username, string password,
            out string message)
        {
            string ldapPath = @"LDAP://" + ldapServer;
            string domainAndUsername = domain + @"\" + username;
            DirectoryEntry entry = new DirectoryEntry(ldapPath, domainAndUsername, password);
            try
            {
                // Bind to the native AdsObject to force authentication.
                Object obj = entry.NativeObject;
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(SAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                SearchResult result = search.FindOne();
                if (null == result)
                {
                    message = "User does not exists";
                    return false;
                }
                // Update the new path to the user in the directory
                ldapPath = result.Path;
            }
            catch (Exception ex)
            {
                message = "Error authenticating user:  " + ex.Message;
                return false;
            }
            message = "User login successfull";
            return true;
        }
        public static string GetStringED(string StrToED, char Action)
        {
            byte[] BytesED;
            TripleDESCryptoServiceProvider ActionED = new TripleDESCryptoServiceProvider();
            //  		 	
            ActionED.Key = new byte[] { 
            0xe4, 0, 0x1d, 0xb6, 0xf1, 250, 0x85, 0x49, 0x1a, 0x1d, 0x92, 0xd5, 0xba, 0xd9, 0xac, 0x1b, 
            0x9a, 0xe4, 0x2e, 0xab, 0xbb, 0x58, 0x81, 0xe7};
            ActionED.IV = new byte[] { 0x77, 0x75, 130, 0xbf, 0xad, 190, 60, 0x34 };
            ActionED.Mode = CipherMode.ECB;
            ActionED.Padding = PaddingMode.PKCS7;

            //
            if (Action == 'E')
            {
                System.Text.ASCIIEncoding ByteStr = new System.Text.ASCIIEncoding();
                BytesED = ByteStr.GetBytes(StrToED);
                ICryptoTransform Transformer = ActionED.CreateEncryptor();
                BytesED = Transformer.TransformFinalBlock(BytesED, 0, BytesED.Length);
                return Convert.ToBase64String(BytesED);
            }
            else
            {
                BytesED = Convert.FromBase64String(StrToED);
                ICryptoTransform Transformer = ActionED.CreateDecryptor();
                BytesED = Transformer.TransformFinalBlock(BytesED, 0, BytesED.Length);
                return System.Text.UTF8Encoding.UTF8.GetString(BytesED);
            }
            //return ByteStr.GetString(BytesED);  		 	
        } // end GetEncryptedString
        /// <summary>
        /// Load a windows form onto a given parent control
        /// </summary>
        /// <param name="FormToLoad">Form to load</param>
        /// <param name="FormParent">Control to stick the form onto</param>
        public static void LoadForm(Form FormToLoad, Control FormParent)
        {
            FormToLoad.TopLevel = false;
            FormToLoad.FormBorderStyle = FormBorderStyle.None;
            FormToLoad.Dock = DockStyle.Fill;
            FormToLoad.Width = FormParent.Width;
            FormToLoad.BackColor = FormSettings.FormBackColor;
            //FormToLoad.BackColor = FormParent.BackColor;
            TabControl tabControl = (FormParent as TabControl);
            if (tabControl != null)
            {
                tabControl.TabPages.Add(FormToLoad.Text);
                //FormToLoad.Text = "";
                FormToLoad.Parent = tabControl.TabPages[tabControl.TabPages.Count - 1];
                tabControl.TabPages[tabControl.TabPages.Count - 1].Select();
            }
            else
                FormToLoad.Parent = FormParent;
            // Set Colors for shell
            LoopAllControlsAndSetColor(FormToLoad);
            // Show form
            FormToLoad.BringToFront();
            FormToLoad.Show();
        }
        public static Color ChangeColor(Color color, int increase)
        {
            const int max = 255;
            //
            int r = Math.Min(color.R - increase, max);
            int g = Math.Min(color.G - increase, max);
            int b = Math.Min(color.B - increase, max);
            //
            return Color.FromArgb(r, g, b);
        }
        /// <summary>
        /// Set form's color to default color scheme, also loop all child controls and set colors
        /// </summary>
        /// <param name="FromToColor"></param>
        public static void LoadFormColor(Form FormToColor)
        {
            // Set Colors for shell
            FormToColor.BackColor = FormSettings.FormBackColor;
            LoopAllControlsAndSetColor(FormToColor);
            if (File.Exists(globePath))
                FormToColor.Icon = new Icon(globePath);
        }
        /// <summary>
        /// Loop a control's children and set colors
        /// </summary>
        /// <param name="ControlToLoop"></param>
        public static void LoopAllControlsAndSetColor(Control ControlToLoop)
        {
            LoopAllControlsAndSetColor(ControlToLoop, true);
        }
        /// <summary>
        /// Loop a control's children and set colors
        /// </summary>
        /// <param name="ControlToLoop"></param>
        /// <param name="addEvents">Add Enter & Leave events</param>
        public static void LoopAllControlsAndSetColor(Control ControlToLoop, bool addEvents)
        {
            Dictionary<int, Font> fonts = new Dictionary<int, Font>();
            fonts.Add((int)HeadingTag.Default, FormSettings.DetailFont);
            fonts.Add((int)HeadingTag.Subheading, FormSettings.SubHeadingFont);
            fonts.Add((int)HeadingTag.Heading, FormSettings.HeadingFont);
            //int tagValue = 0;
            foreach (Control currentControl in ControlToLoop.Controls)
            {
                bool controlTypeFound = false;
                int iTag = (int)HeadingTag.Default;
                if (currentControl.Tag != null)
                {
                    try
                    {
                        iTag = Convert.ToInt32(currentControl.Tag);
                    }
                    catch
                    {
                        //Do Nothing, will leave tag as Default
                    }
                }
                //If the tag is between the ranges of the font enums in which to tag.
                if (iTag != (int)HeadingTag.Ignore && iTag > (int)HeadingTag.FormatStart && iTag < (int)HeadingTag.FormatEnd)
                {
                    currentControl.Font = fonts[iTag];
                    //GroupBox
                    if (currentControl is GroupBox)
                        currentControl.Font = FormSettings.HeadingFont;
                    //TabControl
                    TabControl tbc = currentControl as TabControl;
                    if (tbc != null)
                    {
                        controlTypeFound = true;
                        currentControl.Font = FormSettings.SubHeadingFont;
                        foreach (TabPage tbp in tbc.TabPages)
                            tbp.BackColor = FormSettings.FormBackColor;
                    }
                    //Grid
                    if (!controlTypeFound)
                    {
                        DataGridView gridC = currentControl as DataGridView;
                        controlTypeFound = setThemeGrid(gridC);
                    }
                    //Buttons
                    if (!controlTypeFound)
                    {
                        Button btn = currentControl as Button;
                        controlTypeFound = setThemeButton(btn);
                    }
                    //Labels
                    if (!controlTypeFound)
                    {
                        Label lbl = currentControl as Label;
                        controlTypeFound = setThemeLabel(lbl);
                    }
                    //Text box/ Masked Text box
                    if (!controlTypeFound)
                    {
                        TextBoxBase txt = currentControl as TextBoxBase;
                        controlTypeFound = SetThemeTextBox(txt, addEvents);
                    }
                    //RichTextBox
                    if (!controlTypeFound)
                    {
                        RichTextBox txt = currentControl as RichTextBox;
                        controlTypeFound = SetThemeTextBox(txt, addEvents);
                    }
                    //ComboBox
                    if (!controlTypeFound)
                    {
                        ComboBox cbx = currentControl as ComboBox;
                        controlTypeFound = setThemeComboBox(cbx, addEvents);
                    }
                    //ToolStrip
                    if (!controlTypeFound)
                    {
                        ToolStrip tls = currentControl as ToolStrip;
                        controlTypeFound = setThemeToolStrip(tls);
                    }
                    //StatusStrip
                    if (!controlTypeFound)
                    {
                        StatusStrip sts = currentControl as StatusStrip;
                        if (sts != null)
                        {
                            sts.SizingGrip = false;
                            controlTypeFound = true;
                        }
                    }
                    //Containers
                    if (currentControl is ContainerControl)
                        currentControl.BackColor = FormSettings.FormBackColor;
                    if (currentControl.Controls.Count > 0)
                        LoopAllControlsAndSetColor(currentControl, addEvents);
                }
            }
        }
        /// <summary>
        /// Set "SortMode" on all columns = NotSortable
        /// </summary>
        /// <param name="grid"></param>
        public static void DisableGridSorting(DataGridView grid)
        {
            foreach (DataGridViewColumn col in grid.Columns)
            {
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }
        /// <summary>
        /// This method is used to resize the grid columns to fit the data
        /// </summary>
        /// <param name="grd">Grid to resize</param>
        public static void ResizeGridToData(DataGridView grd)
        {
            foreach (DataGridViewColumn col in grd.Columns)
            {
                if (col.Name != "blankColumn" || !String.IsNullOrEmpty(col.DataPropertyName))
                {
                    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
                }
            }
            grd.Refresh();
            foreach (DataGridViewColumn col in grd.Columns)
            {
                if (col.Name != "blankColumn" || !String.IsNullOrEmpty(col.DataPropertyName))
                {
                    col.Width = col.Width;
                    col.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                }
            }
            grd.AutoResizeColumnHeadersHeight();
        }
        /// <summary>
        /// Set Grid's default colors as per default color scheme
        /// </summary>
        /// <param name="grid"></param>
        public static void SetGridViewColor(DataGridView grid)
        {
            grid.BackgroundColor = FormSettings.GridBackColor;
            grid.EnableHeadersVisualStyles = false;
            grid.AlternatingRowsDefaultCellStyle.BackColor = FormSettings.GridAlternatingRowBC;
            grid.AlternatingRowsDefaultCellStyle.ForeColor = FormSettings.GridAlternatingRowFC;
            grid.RowsDefaultCellStyle.BackColor = FormSettings.GridRowBC;
            grid.RowsDefaultCellStyle.ForeColor = FormSettings.GridRowFC;
            grid.ColumnHeadersDefaultCellStyle.BackColor = FormSettings.GridColumnHeaderBC;
            grid.ColumnHeadersDefaultCellStyle.ForeColor = FormSettings.GridColumnHeaderFC;
            grid.RowHeadersDefaultCellStyle.BackColor = FormSettings.GridRowHeaderBC; // Row indicator

            //
            grid.RowTemplate.Height = DefaultGridRowHeight;
            grid.CellBorderStyle = DataGridViewCellBorderStyle.SingleVertical;
            grid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
            if (DefaultGridHeaderRowHeight <= 0)
                grid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            else
            {
                grid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
                grid.ColumnHeadersHeight = DefaultGridHeaderRowHeight;
            }
            grid.RowHeadersWidth = 25;
        }
        /// <summary>
        /// Set all grid columns not visible, and then set the columns in the view visible
        /// and in the view order.
        /// Note: This relies on the grid columns pre-loaded/created, because it only changes existing columns properies
        /// </summary>
        /// <param name="grid">Grid to set</param>
        /// <param name="view">Columns view string[x,3] - [FieldName, Display Title, Display size]</param>
        public static void SetGridViewColumnsTo(DataGridView grid, string[,] view)
        {
            int d2Length = view.GetUpperBound(1);
            SetGridViewColor(grid);
            if (view != null)
            {
                for (int i = 0; i < grid.Columns.Count; i++)
                {
                    grid.Columns[i].Visible = false;
                }
                for (int i = 0; i <= view.GetUpperBound(0); ++i)
                {
                    grid.Columns[view[i, 0]].Visible = true;
                    grid.Columns[view[i, 0]].HeaderText = view[i, 1];
                    grid.Columns[view[i, 0]].Width = int.Parse(view[i, 2]);
                    grid.Columns[view[i, 0]].DisplayIndex = i;
                    if (d2Length >= 3)
                        SetGridColumnDefaultStyle(grid.Columns[view[i, 0]], view[i, 3]);
                }
            }
        }

        /// <summary>
        /// Clear all current columns and create new grid textbox columns for the view parameter.
        /// Also set grid property "AutoGenerateColumns=false"
        /// Column names = grid.Name + 'c' + view.FieldName
        /// </summary>
        /// <param name="grid">Grid to set</param>
        /// <param name="view">Columns view string[x,3] - [FieldName, Display Title, Display size]</param>
        public static void SetGridColumnsToView(DataGridView grid, string[,] view)
        {
            int d2Length = view.GetUpperBound(1);
            grid.AutoGenerateColumns = false;
            grid.Columns.Clear();
            SetGridViewColor(grid);
            if (view != null)
            {
                for (int i = 0; i <= view.GetUpperBound(0); ++i)
                {
                    DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
                    col.Name = grid.Name + 'c' + view[i, 0];
                    col.DataPropertyName = view[i, 0];
                    col.HeaderText = view[i, 1];
                    col.Width = int.Parse(view[i, 2]);
                    if (d2Length >= 3)
                        SetGridColumnDefaultStyle(col, view[i, 3]);
                    grid.Columns.Add(col);
                }
            }
        }

        /// <summary>
        /// Clear all current columns and create new grid textbox columns for the view parameter.
        /// Also set grid property "AutoGenerateColumns=false"
        /// Column names = grid.Name + 'c' + view.FieldName
        /// </summary>
        /// <param name="grid">Grid to set</param>
        /// <param name="view">Columns view string[x,3] - [FieldName, Display Title, Display size, Format]</param>
        public static void SetGridColumnsToView(DataGridView grid, List<string[]> view)
        {
            grid.AutoGenerateColumns = false;
            grid.Columns.Clear();
            SetGridViewColor(grid);
            if (view != null && view.Count > 0)
            {
                foreach (string[] colView in view)
                {
                    DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
                    col.Name = grid.Name + '_' + colView[0];
                    col.DataPropertyName = colView[0];
                    col.HeaderText = colView[1];
                    col.Width = int.Parse(colView[2]);
                    if (colView.Length >= 4)
                        SetGridColumnDefaultStyle(col, colView[3]);
                    grid.Columns.Add(col);
                }
            }
            else
            {
                grid.AutoGenerateColumns = true;
            }
        }
        /// <summary>
        /// Format a grid column for the data type it carries
        /// </summary>
        /// <param name="column">Column to set</param>
        /// <param name="style">Style: "C" = Currency, Text aligned MiddleRight</param>
        public static void SetGridColumnDefaultStyle(DataGridViewColumn column, string style)
        {
            switch (style)
            {
                case "AR": // Align Right
                    {
                        column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
                        column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; break;
                    }
                case "P":
                case "N":
                case "C":
                    {
                        column.DefaultCellStyle.Format = style;
                        column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
                        column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; break;
                    }
                case "%":
                    {
                        column.DefaultCellStyle.Format = @"###.00\%";
                        column.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
                        column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; break;
                    }
                default:
                    {
                        column.DefaultCellStyle.Format = style; break;
                    }
            }
        }
        /// <summary>
        /// Find and set a control on a form's Visible & Enabled setting
        /// </summary>
        /// <param name="form">Form</param>
        /// <param name="componentName">Component to find</param>
        /// <param name="enabled">Enabled</param>
        /// <param name="visible">Visisble</param>
        /// <returns></returns>
        public static bool SetFormControl(Form form, string componentName, bool enabled, bool visible)
        {
            bool found = false;
            Control[] findControls = form.Controls.Find(componentName, true);
            if (findControls != null && findControls.Length > 0)
            {
                findControls[0].Enabled = enabled;
                findControls[0].Visible = visible;
                found = true;
            }
            return found;
        }
        public static ToolStripItem FindToolStripItem(Form form, string componentName, string parentName)
        {
            if (String.IsNullOrEmpty(parentName))
                return FindToolStripItem(form, componentName);
            else
            {
                ToolStripItem item = null;
                Control[] parent = form.Controls.Find(parentName, true);
                if (parent != null && parent.Length > 0)
                {
                    ToolStrip toolStrip = parent[0] as ToolStrip;
                    if (toolStrip != null)
                    {
                        int j = 0;
                        while (j < toolStrip.Items.Count && item == null)
                        {
                            if (toolStrip.Items[j].Name == componentName)
                            {
                                item = toolStrip.Items[j];
                            }
                            ++j;
                        }
                    }
                }
                return item;
            }
        }
        public static ToolStripItem FindToolStripItem(Form form, string componentName)
        {
            ToolStripItem item = null;
            int i = 0;
            while (i < form.Controls.Count && item == null)
            {
                ToolStrip toolStrip = form.Controls[i] as ToolStrip;
                if (toolStrip != null)
                {
                    int j = 0;
                    while (j < toolStrip.Items.Count && item == null)
                    {
                        if (toolStrip.Items[j].Name == componentName)
                        {
                            item = toolStrip.Items[j];
                        }
                        ++j;
                    }
                }
                ++i;
            }
            return item;
        }
        /// <summary>
        /// Find a ToolStrip component and loop the Items to set Visible & Enabled
        /// </summary>
        /// <param name="form">Form</param>
        /// <param name="componentName">Component to find</param>
        /// <param name="enabled">Enabled</param>
        /// <param name="visible">Visisble</param>
        /// <returns></returns>
        public static bool SetSecurityComponent(Form form, string componentName, bool enabled, bool visible)
        {
            ToolStripItem item = FindToolStripItem(form, componentName);
            if (item != null)
            {
                item.Enabled = enabled;
                item.Visible = visible;
            }
            return item != null;
        }
        public static List<Font> GetFontsFromString(string fontString)
        {
            List<string[]> splitUp = new List<string[]>();
            string[] hashBlocks = fontString.Split('#');
            foreach (string view in hashBlocks)
            {
                splitUp.Add(view.Split(','));
            }
            List<Font> toReturn = new List<Font>();
            foreach (string[] fontSetting in splitUp)
            {
                toReturn.Add(new Font(fontSetting[0], (float)Convert.ToDouble(fontSetting[1]), (FontStyle)Convert.ToByte(fontSetting[2])));
            }
            return toReturn;
        }
        #endregion

        #region - Form Events -
        /// <summary>
        /// When the default colors get set this method will be attached to the text boxes to set the focus color
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">event param</param>
        public static void Txt_Enter(object sender, EventArgs e)
        {
            ((Control)sender).BackColor = FormSettings.InputSelectedBackColor;
        }
        /// <summary>
        /// When the default colors get set this method will be attached to the text boxes to 
        /// set the color back to the default color when the text box looses focus
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">event param</param>
        public static void Txt_Leave(object sender, EventArgs e)
        {
            TextBoxBase txt = (sender as TextBoxBase);
            if (txt != null)
            {
                if (txt.ReadOnly)
                    txt.BackColor = FormSettings.FormBackColor;
                else
                    txt.BackColor = FormSettings.InputBackColor;
            }
            else
                ((Control)sender).BackColor = FormSettings.InputBackColor;
        }
        public static void Txt_OnKeyPress_NoOnly(object sender, KeyPressEventArgs e)
        {
            NumberFormatInfo numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat;
            string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
            string groupSeparator = numberFormatInfo.NumberGroupSeparator;
            string negativeSign = numberFormatInfo.NegativeSign;

            string keyInput = e.KeyChar.ToString();

            if (Char.IsDigit(e.KeyChar))
            {
                // Digits are OK
            }
            else if (keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator) ||
             keyInput.Equals(negativeSign))
            {
                // Decimal separator is OK
            }
            else if (e.KeyChar == '\b')
            {
                // Backspace key is OK
            }
            else
            {
                // Consume this invalid key and beep
                e.Handled = true;
                //    MessageBeep();
            }
        }
		#endregion 
		
    }
    public static class FormSettings
    {
        #region - Public properties / variables
        public static Font DetailFont = new Font("Tahoma", 8.25f);
        public static Font SubHeadingFont = new Font("Tahoma", 9f);
        public static Font HeadingFont = new Font("Tahoma", 9f, FontStyle.Bold);
        public static Color FormBackColor = Color.WhiteSmoke;
        public static Color LabelTextColor = SystemColors.ControlText;
        //public static Color ControlBackColor = Color.WhiteSmoke;
        public static Color InputBackColor = SystemColors.Window;
        //public static Color InputBackColorReadOnly = SystemColors.Control; = FormBackColor
        public static Color InputSelectedBackColor = SystemColors.Window;
        public static Color ButtonBackColor = Color.Transparent;
        public static Color ToolBarBackColor = Color.WhiteSmoke;
        public static Color GridBackColor = SystemColors.AppWorkspace;
        public static Color GridAlternatingRowBC = Color.WhiteSmoke;
        public static Color GridAlternatingRowFC = Color.Black;
        public static Color GridRowBC = Color.White;
        public static Color GridRowFC = Color.Black;
        public static Color GridColumnHeaderBC = Color.Silver;
        public static Color GridColumnHeaderFC = Color.Black;
        public static Color GridRowHeaderBC = Color.Gray; // Row Indicator
        #endregion

        #region - Public methods -
        public static void SetColors(Color formColor, Color toolbar,
            Color labelTextColor, Color inputBackColor, Color inputSelectedBackColor,
            Color gridColor, Color gridAlterRow, Color gridColumnHead, Color gridRowHead, Color gridRowDefault)
        {
            FormSettings.FormBackColor = (formColor.ToArgb() == 0 ? SystemColors.Control : formColor);
            FormSettings.ToolBarBackColor = (toolbar.ToArgb() == 0 ? Color.WhiteSmoke : toolbar);
            FormSettings.LabelTextColor = (labelTextColor.ToArgb() == 0 ? Color.Black : labelTextColor);
            FormSettings.InputBackColor = (inputBackColor.ToArgb() == 0 ? Color.White : inputBackColor);
            FormSettings.InputSelectedBackColor = (inputSelectedBackColor.ToArgb() == 0 ? Color.White : inputSelectedBackColor);
            FormSettings.GridBackColor = (gridColor.ToArgb() == 0 ? SystemColors.AppWorkspace : gridColor);
            FormSettings.GridAlternatingRowBC = (gridAlterRow.ToArgb() == 0 ? Color.WhiteSmoke : gridAlterRow);
            FormSettings.GridColumnHeaderBC = (gridColumnHead.ToArgb() == 0 ? Color.Silver : gridColumnHead);
            FormSettings.GridRowHeaderBC = (gridRowHead.ToArgb() == 0 ? Color.Gray : gridRowHead);
            FormSettings.GridRowBC = (gridRowDefault.ToArgb() == 0 ? Color.White : gridRowDefault);
            FormSettings.GridAlternatingRowFC = Color.Black;
            FormSettings.GridColumnHeaderFC = Color.Black;
            FormSettings.GridRowFC = Color.Black;
            FormSettings.DetailFont = new Font("Tahoma", 8.25f);
            FormSettings.SubHeadingFont = new Font("Tahoma", 9f);
            FormSettings.HeadingFont = new Font("Tahoma", 9f, FontStyle.Bold);
        }
        public static void SetColors(Color formColor, Color toolbar, Color labelTextColor, Color inputBackColor, Color inputSelectedBackColor,
            Color gridColor, Color gridAlterRowBC, Color gridAlterRowFC, Color gridColumnHeadBC, Color gridColumnHeadFC, Color gridRowHead,
            Color gridRowDefaultBC, Color gridRowDefaultFC, Font detail, Font subHeading, Font heading)
        {
            FormSettings.SetColors(formColor, toolbar, labelTextColor, inputBackColor, inputSelectedBackColor, gridColor, gridAlterRowBC, gridColumnHeadBC, gridRowHead, gridRowDefaultBC);
            FormSettings.GridAlternatingRowFC = gridAlterRowFC;
            FormSettings.GridColumnHeaderFC = gridColumnHeadFC;
            FormSettings.GridRowFC = gridRowDefaultFC;

            FormSettings.DetailFont = detail ?? FormSettings.DetailFont;
            FormSettings.SubHeadingFont = subHeading ?? FormSettings.DetailFont;
            FormSettings.HeadingFont = heading ?? FormSettings.DetailFont;
        }
        public static void SetColors(Color formColor, Color toolbar, Color labelTextColor, Color inputBackColor, Color inputSelectedBackColor,
          Color gridColor, Color gridAlterRowBC, Color gridAlterRowFC, Color gridColumnHeadBC, Color gridColumnHeadFC, Color gridRowHead,
          Color gridRowDefaultBC, Color gridRowDefaultFC, string fontString)
        {

            List<Font> fonts = General.GetFontsFromString(fontString);
            if (fonts.Count == 3)
                FormSettings.SetColors(formColor, toolbar, labelTextColor, inputBackColor, inputSelectedBackColor, gridColor, gridAlterRowBC, gridAlterRowFC,
                    gridColumnHeadBC, gridColumnHeadFC, gridRowHead, gridRowDefaultBC, gridRowDefaultFC, fonts[0], fonts[1], fonts[2]);
            else
                FormSettings.SetColors(formColor, toolbar, labelTextColor, inputBackColor, inputSelectedBackColor, gridColor, gridAlterRowBC, gridAlterRowFC,
                    gridColumnHeadBC, gridColumnHeadFC, gridRowHead, gridRowDefaultBC, gridRowDefaultFC, null, null, null);
        }
        public static void SetDefault()
        {
            FormSettings.SetColors(Color.WhiteSmoke, SystemColors.Control,
                SystemColors.ControlText, SystemColors.Window, SystemColors.Window,
                // Grid colors
                SystemColors.AppWorkspace,
                Color.LightSteelBlue, Color.FromArgb(-2697815),
                Color.FromArgb(-1447218), Color.White);
        }
        public static void SetThemeKhaki()
        {
            FormSettings.SetColors(Color.FromArgb(-1447976), Color.FromArgb(-2764621),
                Color.FromArgb(-11980255), Color.FromArgb(-987179), Color.White,
                // Grid colors
                SystemColors.AppWorkspace,
                Color.FromArgb(-2040665), Color.FromArgb(-2697815),
                Color.FromArgb(-1447218), Color.FromArgb(-789289));
        }
        public static void SetThemeGreen()
        {
            FormSettings.SetColors(Color.FromArgb(-1511972), Color.FromArgb(-3024470),
                Color.FromArgb(-16759261), Color.FromArgb(-525840), Color.White,
                // Grid colors
                SystemColors.AppWorkspace,
                Color.FromArgb(-2167103), Color.FromArgb(-3744841),
                Color.FromArgb(-1447218), Color.FromArgb(-1));
        }
        public static void SetThemeBlue()
        {
            FormSettings.SetColors(Color.FromArgb(-789000), Color.AliceBlue,
                Color.FromArgb(-13874568), Color.FromArgb(-2760210), Color.White,
                // Grid colors
                SystemColors.AppWorkspace,
                Color.FromArgb(-5192482), Color.FromArgb(-6836276),
                Color.FromArgb(-3284245), Color.FromArgb(-1379849));
        }
        #endregion
        
    }

}
